#!/bin/bash

# 设置变量
APP_NAME="worktool"
APP_DIR="/opt/worktool"
BACKUP_DIR="/backup/worktool"
CONFIG_FILE="config/config.prod.yaml"
LOG_DIR="logs"

# 颜色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

# 检查root权限
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}请使用root权限运行此脚本${NC}"
    exit 1
fi

# 创建必要目录
echo -e "${GREEN}创建目录...${NC}"
mkdir -p $APP_DIR
mkdir -p $BACKUP_DIR
mkdir -p $APP_DIR/$LOG_DIR

# 安装依赖
echo -e "${GREEN}安装依赖...${NC}"
apt-get update
apt-get install -y mysql-server redis-server

# 备份旧版本
if [ -f "$APP_DIR/server" ]; then
    echo -e "${GREEN}备份旧版本...${NC}"
    cp $APP_DIR/server $BACKUP_DIR/server.$(date +%Y%m%d_%H%M%S)
fi

# 编译项目
echo -e "${GREEN}编译项目...${NC}"
go mod download
go build -o server cmd/main.go

# 复制文件
echo -e "${GREEN}复制文件...${NC}"
cp server $APP_DIR/
cp -r config $APP_DIR/
cp -r static $APP_DIR/

# 设置权限
echo -e "${GREEN}设置权限...${NC}"
chown -R worktool:worktool $APP_DIR
chmod +x $APP_DIR/server

# 创建服务文件
echo -e "${GREEN}创建服务文件...${NC}"
cat > /etc/systemd/system/worktool.service << EOF
[Unit]
Description=WorkTool Server
After=network.target mysql.service redis.service

[Service]
Type=simple
User=worktool
WorkingDirectory=$APP_DIR
ExecStart=$APP_DIR/server -config $CONFIG_FILE
Restart=always
RestartSec=5
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

# 重载服务
echo -e "${GREEN}重载服务...${NC}"
systemctl daemon-reload
systemctl enable worktool
systemctl restart worktool

# 检查服务状态
echo -e "${GREEN}检查服务状态...${NC}"
systemctl status worktool

echo -e "${GREEN}部署完成！${NC}" 